﻿using System;
using System.Configuration;
using System.Web;
using System.Web.Routing;

namespace K3R.Web.Routing {
	public class RoutingModule : IHttpModule {

		public void Init(HttpApplication context) {
			RegisterRoutes(RouteTable.Routes);
		}

		private void RegisterRoutes(RouteCollection routes) {
			var routing = ConfigurationManager.GetSection("k3r.web.routing") as RouteConfig;
			if (routing != null) {
				routes.RouteExistingFiles = routing.RouteExisting;
				routes.Clear();

				if (routing.IgnoreFavicon)
					routes.IgnoreRoute("favicon.ico/{*pathInfo}");

				if (routing.IgnoreAxd)
					routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

				if (routing.IgnoreAsmx)
					routes.IgnoreRoute("{resource}.asmx/{*pathInfo}");

				foreach (ConfigRouteElement route in routing.Routes)
					if (route.Ignore)
						routes.IgnoreRoute(route.Url);
					else {
						var virtualPath = route.VirtualPath != "" ? route.VirtualPath : routing.VirtualPath;
						var handler = route.Handler != "" ? route.Handler : routing.Handler;
						var type = handler.Split(',');

						IVirtualRouteHandler routeHandler;
						if (type.Length == 2)
							routeHandler = Activator.CreateInstance(type[1], type[0]).Unwrap() as IVirtualRouteHandler;
						else routeHandler = Activator.CreateInstance(Type.GetType(handler)) as IVirtualRouteHandler;

						if (routeHandler != null) {
							if (virtualPath != null)
								routeHandler.SetVirtualPath(virtualPath);

							routes.Add(new Route(route.Url, routeHandler));
						}
						else throw new Exception("Route Handler not recognised.");
					}

			}
		}

		public void Dispose() { }
	}
}